<template>
	<view class="container">
		<!-- 顶部粘性区域：标题 + 筛选 -->
		<view class="sticky-header">
			<view class="page-header">
				<text class="page-title">{{ studentName }} · 课时记录</text>
				<text class="page-subtitle">实时 · 准确 · 可追溯</text>
			</view>

			<!-- 筛选器 -->
			<view class="filter-section">
				<view class="filter-tabs">
					<view
						class="filter-tab"
						:class="{ active: currentFilter === 'all' }"
						@click="setFilter('all')"
					>
						<text class="tab-text">全部</text>
					</view>
					<view
						class="filter-tab"
						:class="{ active: currentFilter === 'use' }"
						@click="setFilter('use')"
					>
						<text class="tab-text">使用</text>
					</view>
					<view
						class="filter-tab"
						:class="{ active: currentFilter === 'recharge' }"
						@click="setFilter('recharge')"
					>
						<text class="tab-text">充值</text>
					</view>
					<view
						class="filter-tab"
						:class="{ active: currentFilter === 'adjust' }"
						@click="setFilter('adjust')"
					>
						<text class="tab-text">调整</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 统计信息 -->
		<view class="stats-section">
			<view class="stats-grid">
				<view class="stats-item glass">
					<text class="stats-number gradient-text">{{ stats.totalRecords }}</text>
					<text class="stats-label">总记录</text>
				</view>
				<view class="stats-item glass">
					<text class="stats-number gradient-text">{{ stats.totalRecharge }}</text>
					<text class="stats-label">总充值</text>
				</view>
				<view class="stats-item glass">
					<text class="stats-number gradient-text">{{ stats.totalUsed }}</text>
					<text class="stats-label">总使用</text>
				</view>
			</view>
		</view>

		<!-- 骨架屏 -->
		<view v-if="loading" class="skeleton-list">
			<view class="skeleton-item" v-for="n in 6" :key="n">
				<view class="skeleton-icon shimmer"></view>
				<view class="skeleton-lines">
					<view class="skeleton-line shimmer" style="width: 60%"></view>
					<view class="skeleton-line shimmer" style="width: 40%"></view>
				</view>
				<view class="skeleton-amount shimmer"></view>
			</view>
		</view>

		<!-- 记录列表 -->
		<scroll-view
			v-else
			class="record-scroll"
			scroll-y="true"
			@scrolltolower="onLoadMore"
			refresher-enabled="true"
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="record-list">
				<view v-if="decoratedLogs.length === 0" class="empty-records">
					<text class="empty-icon">📄</text>
					<text class="empty-text">暂无课时记录</text>
					<text class="empty-desc">这里将展示该学生所有与课时相关的充值、使用及调整记录</text>
				</view>

				<view class="record-item" v-for="item in decoratedLogs" :key="item.id">
					<view class="record-accent" :class="item.typeClass"></view>
					<view class="record-icon">
						<text class="icon-text" :class="item.typeClass">{{ getRecordIcon(item) }}</text>
					</view>
					<view class="record-info">
						<text class="record-title">{{ item.title || '记录' }}</text>
						<text class="record-time">{{ formatTime(item.time) }}</text>
						<text v-if="item.description" class="record-desc">{{ item.description }}</text>
						<text v-if="item.adminId" class="record-admin">操作员: {{ item.adminId }}</text>
					</view>
					<view class="record-amount">
						<text class="amount-chip" :class="item.typeClass">{{ item.changeValue > 0 ? '+' : '' }}{{ item.changeValue }}</text>
					</view>
				</view>

				<!-- 加载更多 -->
				<view v-if="hasMore && decoratedLogs.length > 0" class="load-more">
					<text class="load-text">加载中...</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { getApiUrl, API_CONFIG, apiRequest } from '@/config/api.js'

export default {
	data() {
		return {
			studentId: null,
			studentName: '',
			lessonLogs: [],
			filteredLogs: [],
			currentFilter: 'all',
			isRefreshing: false,
			hasMore: true,
			page: 1,
			pageSize: 20,
			loading: false,
			stats: {
				totalRecords: 0,
				totalRecharge: 0,
				totalUsed: 0
			}
		}
	},
	computed: {
		decoratedLogs() {
			return (this.filteredLogs || []).map(log => {
				const change = log.changeValue || 0
				const typeClass = change > 0 ? 'recharge' : (change < 0 ? 'use' : (log.type === 'ADJUSTMENT' ? 'adjust' : 'default'))
				return { ...log, typeClass }
			})
		}
	},
	onLoad(options) {
		console.log('接收到的参数:', options)
		if (options.studentId) {
			this.studentId = options.studentId
		}
		if (options.studentName) {
			// 解码URL编码的中文字符
			this.studentName = decodeURIComponent(options.studentName)
			console.log('解码后的学生姓名:', this.studentName)
		}
		this.loadLessonLogs()
	},
	methods: {
		async loadLessonLogs(refresh = false) {
			if (this.loading) return
			this.loading = true
			try {
				const token = uni.getStorageSync('token')
				const response = await apiRequest({
					url: getApiUrl(API_CONFIG.ENDPOINTS.LESSON_LOGS),
					method: 'GET',
					header: {
						'Content-Type': 'application/json',
						'Authorization': `Bearer ${token}`
					},
					data: { studentId: this.studentId, page: refresh ? 1 : this.page, pageSize: this.pageSize }
				})
				if (response.code === 200) {
					const newLogs = response.data || []
					if (refresh) {
						this.lessonLogs = newLogs
						this.page = 1
					} else {
						this.lessonLogs = [...this.lessonLogs, ...newLogs]
						this.page++
					}
					this.hasMore = newLogs.length === this.pageSize
					this.applyFilter()
					this.calculateStats()
				} else {
					uni.showToast({ title: response.message || '获取课时记录失败', icon: 'none' })
				}
			} catch (error) {
				console.error('获取课时记录失败:', error)
				uni.showToast({ title: '网络错误，请重试', icon: 'none' })
			} finally {
				this.loading = false
				this.isRefreshing = false
			}
		},

		onRefresh() { this.isRefreshing = true; this.loadLessonLogs(true) },
		onLoadMore() { if (this.hasMore && !this.loading) { this.loadLessonLogs() } },

		setFilter(filter) { this.currentFilter = filter; this.applyFilter() },

		applyFilter() {
			if (this.currentFilter === 'all') {
				this.filteredLogs = [...this.lessonLogs]
				return
			}
			this.filteredLogs = this.lessonLogs.filter(log => {
				if (this.currentFilter === 'recharge') return (log.changeValue || 0) > 0
				if (this.currentFilter === 'use') return (log.changeValue || 0) < 0
				if (this.currentFilter === 'adjust') return log.type === 'ADJUSTMENT'
				return true
			})
		},

		calculateStats() {
			this.stats.totalRecords = this.lessonLogs.length
			this.stats.totalRecharge = this.lessonLogs.filter(log => (log.changeValue || 0) > 0).length
			this.stats.totalUsed = this.lessonLogs.filter(log => (log.changeValue || 0) < 0).length
		},

		getRecordIcon(item) {
			if ((item.changeValue || 0) > 0) return '💰'
			if ((item.changeValue || 0) < 0) return '📖'
			if (item.type === 'ADJUSTMENT') return '⚙️'
			return '📝'
		},

		formatTime(timeStr) {
			if (!timeStr) return ''
			const date = new Date(timeStr)
			const now = new Date()
			const diffTime = now - date
			const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
			if (diffDays === 0) {
				return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
			} else if (diffDays === 1) {
				return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
			} else if (diffDays < 7) {
				return `${diffDays}天前`
			} else {
				return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: radial-gradient(1200rpx 600rpx at 10% 0%, rgba(33, 150, 243, 0.12), transparent 60%),
		linear-gradient(135deg, #0B0F1A 0%, #121725 50%, #1a1f2e 100%);
	display: flex;
	flex-direction: column;
}

.sticky-header {
	position: sticky;
	top: 0;
	z-index: 50;
	background: linear-gradient(180deg, rgba(18,23,37,.96), rgba(18,23,37,.92) 60%, rgba(18,23,37,0));
	backdrop-filter: saturate(140%);
}

.page-header {
	padding: 34rpx 20rpx 14rpx;
	.page-title { font-size: 36rpx; color: #FFFFFF; font-weight: 800; letter-spacing: .5rpx; }
	.page-subtitle { display:block; margin-top: 8rpx; font-size: 22rpx; color: #AAB4BE; opacity: .8; }
}

.filter-section { padding: 8rpx 20rpx 16rpx; }
.filter-tabs { display: flex; background: linear-gradient(135deg, #121827 0%, #161d2d 100%); border-radius: 16rpx; padding: 8rpx; border: 2rpx solid rgba(102,175,233,.18); box-shadow: inset 0 1rpx 0 rgba(255,255,255,.03); }
.filter-tab { flex: 1; padding: 16rpx 20rpx; text-align: center; border-radius: 12rpx; transition: all .25s ease; }
.filter-tab.active { background: linear-gradient(135deg, #1976D2 0%, #00B8D4 100%); box-shadow: 0 6rpx 18rpx rgba(0, 184, 212, .28); }
.filter-tab .tab-text { font-size: 26rpx; color: #AAB4BE; }
.filter-tab.active .tab-text { color: #fff; font-weight: 600; }

.stats-section { margin: 16rpx 20rpx 8rpx; }
.stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16rpx; }
.stats-item { background: #131a2a; border-radius: 18rpx; padding: 26rpx 20rpx; text-align: center; border: 2rpx solid rgba(102,175,233,.18); box-shadow: 0 12rpx 36rpx rgba(0,0,0,.35); }
.stats-number { display:block; font-size: 32rpx; color: #fff; font-weight: 800; margin-bottom: 6rpx; }
.stats-label { font-size: 22rpx; color: #AAB4BE; }

.gradient-text { background: linear-gradient(90deg, #6ee7f9, #60a5fa, #a78bfa); -webkit-background-clip: text; background-clip: text; color: transparent; }

/* 骨架屏 */
.skeleton-list { padding: 20rpx; display: grid; gap: 16rpx; }
.skeleton-item { display: grid; grid-template-columns: 60rpx 1fr 120rpx; align-items: center; gap: 16rpx; background: #141b2c; border: 2rpx solid rgba(102,175,233,.16); border-radius: 16rpx; padding: 22rpx; }
.skeleton-icon { width: 60rpx; height: 60rpx; border-radius: 50%; background: #1f2740; }
.skeleton-lines { display: grid; gap: 12rpx; }
.skeleton-line { height: 22rpx; border-radius: 12rpx; background: #1f2740; }
.skeleton-amount { width: 120rpx; height: 40rpx; border-radius: 24rpx; background: #1f2740; justify-self: end; }
@keyframes shimmer { 0%{opacity:.5} 50%{opacity:.9} 100%{opacity:.5} }
.shimmer { animation: shimmer 1.6s ease-in-out infinite; }

.record-scroll { flex: 1; height: 0; }

.record-list { padding: 8rpx 20rpx 40rpx; }
.empty-records { background: #141b2c; border-radius: 18rpx; padding: 120rpx 30rpx; text-align: center; border: 2rpx solid rgba(102,175,233,.16); margin-top: 20rpx; box-shadow: 0 12rpx 36rpx rgba(0,0,0,.35); }
.empty-icon { font-size: 100rpx; display:block; margin-bottom: 16rpx; opacity: .6; }
.empty-text { font-size: 30rpx; color: #fff; font-weight: 800; margin-bottom: 10rpx; }
.empty-desc { font-size: 24rpx; color: #AAB4BE; }

.record-item { position: relative; background: linear-gradient(180deg, #141b2c, #121827); border-radius: 18rpx; padding: 24rpx; margin-bottom: 16rpx; display: grid; grid-template-columns: 60rpx 1fr 120rpx; align-items: center; border: 2rpx solid rgba(102,175,233,.18); box-shadow: 0 16rpx 36rpx rgba(0,0,0,.35); }
.record-accent { position: absolute; left: 0; top: 0; bottom: 0; width: 6rpx; border-top-left-radius: 18rpx; border-bottom-left-radius: 18rpx; }
.record-accent.use { background: linear-gradient(180deg, #ef4444, #f59e0b); }
.record-accent.recharge { background: linear-gradient(180deg, #10b981, #22d3ee); }
.record-accent.adjust { background: linear-gradient(180deg, #f59e0b, #fbbf24); }
.record-accent.default { background: linear-gradient(180deg, #64748b, #94a3b8); }

.record-icon { width: 60rpx; height: 60rpx; border-radius: 50%; background: #1e2741; display:flex; align-items:center; justify-content:center; border: 2rpx solid rgba(102,175,233,.18); }
.icon-text { font-size: 30rpx; }
.icon-text.use { color: #f87171; }
.icon-text.recharge { color: #34d399; }
.icon-text.adjust { color: #f59e0b; }
.icon-text.default { color: #AAB4BE; }

.record-info { padding: 0 16rpx; }
.record-title { display:block; font-size: 28rpx; color: #FFFFFF; margin-bottom: 6rpx; font-weight: 700; }
.record-time { display:block; font-size: 22rpx; color: #AAB4BE; margin-bottom: 6rpx; }
.record-desc { display:block; font-size: 22rpx; color: rgba(170, 180, 190, 0.85); }
.record-admin { display:block; font-size: 20rpx; color: rgba(170, 180, 190, 0.6); margin-top: 4rpx; }

.record-amount { justify-self: end; }
.amount-chip { display:inline-block; min-width: 120rpx; text-align:center; padding: 10rpx 16rpx; border-radius: 24rpx; font-weight: 700; font-size: 26rpx; border: 2rpx solid transparent; }
.amount-chip.use { background: rgba(248, 113, 113, .12); color: #fca5a5; border-color: rgba(248, 113, 113, .32); }
.amount-chip.recharge { background: rgba(52, 211, 153, .12); color: #86efac; border-color: rgba(52, 211, 153, .32); }
.amount-chip.adjust { background: rgba(245, 158, 11, .12); color: #fcd34d; border-color: rgba(245, 158, 11, .32); }
.amount-chip.default { background: rgba(148, 163, 184, .12); color: #cbd5e1; border-color: rgba(148, 163, 184, .32); }
</style>
